﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.ServiceModel;
using CMS.Contracts;
using CMS.Model;
namespace CMS.Presentation
{
    public partial class CourseManage : System.Web.UI.Page
    {
        public int PageIndex = 1;
        public int PageSize = 5;
        public int RowCount;
        public int PageCount = 1;
        public string CourseName;
        public string CourseStatus;
        /// <summary>
        /// PageLoad Show all the Course Records int the gridview
        /// </summary>
        /// <param name="sender">object sender</param>
        /// <param name="e">EventArgs e</param>
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                ViewState["CurrentPage"] = PageIndex;
                GridViewBind();
            }

        }

        /// <summary>
        /// Select the required records and show them in the gridview
        /// </summary>
        /// <param name="sender">Object sender</param>
        /// <param name="e">EvenArgs e</param>
        protected void SearchButton_Click(object sender, EventArgs e)
        {
            GetSearchCondition();
            SearchMessageLabel.Visible = false;
            ReturnHyperLink.Visible = false;
            GridViewBind();
            if (CourseListGridView.Rows.Count == 0)
            {
                CreateCourseButton.Visible = false;
                ChangeStatusButton.Visible = false;
                SearchMessageLabel.Visible = true;
                ReturnHyperLink.Visible = true;
                ItemLabel.Visible = false;
                PageLabel.Visible = false;
                NextLinkButton.Visible = false;
                LastPageLinkButton.Visible = false;
            }
            else
            {
                CreateCourseButton.Visible = true;
                ChangeStatusButton.Visible = true;
                ItemLabel.Visible = true;
                PageLabel.Visible = true;
            }
        }
        #region
        /// <summary>
        /// Set the gridview format and bind the javascript when binding data
        /// </summary>
        /// <param name="sender">Object Sender</param>
        /// <param name="e">GridViewRowEventArgs e</param>
        protected void CourseListGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //Set the gridview format
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label labelStatus = (Label)e.Row.FindControl("StatusLabel");
                string courseStatus = labelStatus.Text.Trim().ToLower();
                if (courseStatus == "closed")
                {
                    ((CheckBox)e.Row.FindControl("StatusCheckBox")).Enabled = false;
                    ((Button)e.Row.FindControl("DeleteButton")).Attributes.Add("onclick", "return confirm('Are you sure to delete this?')");
                }

                else
                    ((Button)e.Row.FindControl("DeleteButton")).Attributes.Add("onclick", "alert('Open course is not allowed deleted！');return false;");

            }
        }


        /// <summary>
        /// RowDeleting delete the selected coloum based on the Id
        /// </summary>
        /// <param name="sender">object sender</param>
        /// <param name="e">GridViewDeleteEventArgs e</param>
        protected void CourseListGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int deleteId = Convert.ToInt32(CourseListGridView.DataKeys[e.RowIndex].Value.ToString());
            using (ChannelFactory<IProjectBService> channelFactory = new ChannelFactory<IProjectBService>("CMSClient"))
            {
                IProjectBService iProjectBService = channelFactory.CreateChannel();
                using (iProjectBService as IDisposable)
                {
                    iProjectBService.DeleteCourseById(deleteId);
                }
            }
            GridViewBind();

        }
        protected void CourseListGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int id = Convert.ToInt32(CourseListGridView.DataKeys[e.RowIndex].Value.ToString());
            Response.Redirect("SaveCourse.aspx?courseId=" + id);

        }
        /// <summary>
        /// ChangeStatus batch change open to close
        /// </summary>
        /// <param name="sender">object sender</param>
        /// <param name="e">EventArgs e</param>
        protected void ChangeStatusButton_Click(object sender, EventArgs e)
        {

            using (ChannelFactory<IProjectBService> channelFactory = new ChannelFactory<IProjectBService>("CMSClient"))
            {
                IProjectBService iProjectBService = channelFactory.CreateChannel();
                using (iProjectBService as IDisposable)
                {
                    for (int i = 0; i < CourseListGridView.Rows.Count; i++)
                    {
                        CheckBox checkbox = (CheckBox)CourseListGridView.Rows[i].FindControl("StatusCheckBox");
                        string statusLabelValue = ((Label)CourseListGridView.Rows[i].FindControl("StatusLabel")).Text.Trim();
                        if (checkbox.Checked == true && statusLabelValue == "Open")
                        {
                            Course course = new Course();
                            course.CourseId = Convert.ToInt32(CourseListGridView.DataKeys[i].Value);
                            course.CourseStatus = true;
                            iProjectBService.ChangeCourseStatus(course);
                        }

                    }

                }
            }
            CourseNameTextBox.Text = "";
            GridViewBind();
        }
        #endregion
        protected void SetLinkButtonState(int pageIndex)
        {
            int _pageIndex = pageIndex;
            if (_pageIndex == 1)
            {
                FirstPageLinkButton.Visible = false;
                PreviousLinkButton.Visible = false;
            }
            else
            {
                FirstPageLinkButton.Visible = true;
                PreviousLinkButton.Visible = true;
            }
            if (_pageIndex == PageCount)
            {
                LastPageLinkButton.Visible = false;
                NextLinkButton.Visible = false;
            }
            else
            {
                LastPageLinkButton.Visible = true;
                NextLinkButton.Visible = true;
            }
        }
        protected void PageLinkButton_Click(object sender, EventArgs e)
        {
            string commandName = ((LinkButton)sender).CommandName;
            PageCount = ((int)ViewState["rowCount"] + PageSize - 1) / PageSize;
            switch (commandName)
            {
                case "First":
                    ViewState["CurrentPage"] = 1;
                    break;
                case "Previous":
                    ViewState["CurrentPage"] = (int)ViewState["CurrentPage"] - 1;
                    break;
                case "Next":
                    ViewState["CurrentPage"] = (int)ViewState["CurrentPage"] + 1;
                    break;
                case "Last":
                    ViewState["CurrentPage"] = PageCount;
                    break;
            }
            PageIndex = (int)ViewState["CurrentPage"];
            GridViewBind();
        }
        /// <summary>
        /// GridviewBind
        /// Bind the data to gridview in different situations
        /// </summary>
        protected void GridViewBind()
        {
            using (ChannelFactory<IProjectBService> channelFactory = new ChannelFactory<IProjectBService>("CMSClient"))
            {
                IProjectBService iProjectBService = channelFactory.CreateChannel();
                using (iProjectBService as IDisposable)
                {
                    CourseListGridView.DataSource = iProjectBService.GetCoursesByCondition(CourseName,CourseStatus,PageIndex,PageSize,out RowCount);
                    CourseListGridView.DataKeyNames = new string[] { "CourseId" };
                    CourseListGridView.DataBind();
                }
                ViewState["rowCount"] = RowCount;
                ItemLabel.Text = string.Format("Total Items of Course is :{0}", RowCount);
                PageCount = (RowCount + PageSize - 1) / PageSize;
                PageLabel.Text = string.Format("{0}/{1}", PageIndex, (RowCount + PageSize - 1) / PageSize);
                SetLinkButtonState(PageIndex);
            }
        }
        protected void GetSearchCondition()
        {
            CourseName = CourseNameTextBox.Text.Trim();
            CourseStatus = StatusRadioButtonList.SelectedValue;
        }
    }
}
